# coding=utf-8

import sys
import time
import datetime

from builtins import int

sys.path.append("..")
from common.mysql.connect import MysqlConnector
from common.tdengine.connect import TdengineConnector
from common.redis.connect import RedisConnector
from common.utils.time import turn_ts_to_date
from common.utils.time import get_yesterday_date
from common.utils.time import turn_date_to_ts
from models.manager import get_dict_of_mid_and_bid


def get_stock_info(mysql_db):
    """ 获取商品库存信息
    """
    goods_stock_sql = "SELECT id,lx_id,num,k_price FROM ko_stock WHERE num > 0 AND lx_id IN (1,2,5)"
    goods_stock_res = mysql_db.select(goods_stock_sql)
    return goods_stock_res
    

def snatshot(mysql_db, stock_info, date):
    """ 保存快照
    """
    date_ts = turn_date_to_ts(date)
    sql_init = "INSERT INTO stock_info (date, goods_id, goods_type, goods_brand, \
        goods_num, goods_value) VALUES "
    num = 1
    stock_info_len = len(stock_info)
    for stock in stock_info:
        if stock['lx_id'] == 1:
            goods_brand = 1
        else:
            goods_brand = 2

        if num == stock_info_len:
            sql_init += " (%d, %d, %d, %d, %d, %f) " % \
                (date_ts, stock['id'], 1, goods_brand, stock['num'], stock['num'] * stock['k_price'])
        else:
            sql_init += " (%d, %d, %d, %d, %d, %f), " % \
                (date_ts, stock['id'], 1, goods_brand, stock['num'], stock['num'] * stock['k_price'])
        num += 1
    res = mysql_db.execute(sql_init)
    return res


if __name__ == '__main__':
    """ 商品(包括散珠配石和首饰盒)库存快照，每日留存，只保留有库存的商品
    """
    # 获取要处理的日期
    if len(sys.argv) == 2:
        # 外部传递进来
        date = sys.argv[1]
    else :
        # 默认取前一天的日期
        date = datetime.datetime.strftime(get_yesterday_date(), "%Y-%m-%d")

    redis_14 = RedisConnector(14)
    mysql_db = MysqlConnector(1)
    mysql_db2 = MysqlConnector(2)

    # 保存库存信息快照
    stock_info = get_stock_info(mysql_db)
    res = snatshot(mysql_db2, stock_info, date)
    print(res)
    # print(len(res))
